import { useEffect, useState } from "react";

const useKeyPress = (targetKeyCode) => {
    const [keyPressed, setKeyPressed] = useState(false);
    useEffect(() => {
        // 按下
        const keyDownHandler = ({ keyCode }) => {
            // console.log("按下");
            if (keyCode === targetKeyCode) {
                setKeyPressed(true);
            }
        };

        // 抬起
        const keyUpHandler = ({ keyCode }) => {
            // console.log("抬起");
            if (keyCode === targetKeyCode) {
                setKeyPressed(false);
            }
        };
        document.addEventListener("keydown", keyDownHandler);
        document.addEventListener("keyup", keyUpHandler);
        return () => {
            document.removeEventListener("keydown", keyDownHandler);
            document.removeEventListener("keyup", keyUpHandler);
        };
    }, [targetKeyCode]);
    return keyPressed;
};

export default useKeyPress;
